package edu.uestc.canary.service.bean;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import edu.uestc.canary.entity.dto.BookParams;
import edu.uestc.canary.entity.dto.Result;
import edu.uestc.canary.entity.pojo.Book;
import edu.uestc.canary.repository.mapper.BookMapper;
import edu.uestc.canary.service.BookService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class BookServiceBean extends ServiceImpl<BookMapper, Book> implements BookService {
    @Override
    public Result pagination(BookParams bookParams) {
        var wrapper = new LambdaQueryWrapper<Book>()
                .like(StringUtils.hasLength(bookParams.getTitle()), Book::getTitle, bookParams.getTitle())
                .or()
                .eq(StringUtils.hasLength(bookParams.getAuthor()), Book::getAuthor, bookParams.getAuthor())
                .ge(bookParams.getLowPrice() > 0, Book::getSellPrice, bookParams.getLowPrice())
                .le(bookParams.getHighPrice() > 0 && bookParams.getHighPrice() > bookParams.getLowPrice(), Book::getSellPrice, bookParams.getHighPrice());
        var page = new Page<Book>(bookParams.getPageIndex(), bookParams.getPageSize());
        if (StringUtils.hasLength(bookParams.getSorted()))
            page.addOrder(bookParams.isAsc() ? OrderItem.asc(bookParams.getSorted()) : OrderItem.desc(bookParams.getSorted()));
        //page.setRecords(list(page, wrapper));
        page(page, wrapper);
        return Result.ok(page);
    }
}
